import {Body, Controller, Get, HttpStatus, Post, Query, Res} from '@nestjs/common';
import {Response} from 'express';
import {CommonResponseDto} from '../../dto/common.response.dto';
import {ApplyStatus, ApproveStatus, ResCode} from '../../common/constants';
import {ApproveService} from "../../service/approve.service";
import {ApplyService} from "../../service/apply.service";
import {ApplyUserService} from "../../service/apply.user.service";
import {ApproveDto} from "../../dto/approve.dto";
import {formatTime, uuid} from "../../common/utils";
import {CommonRedisService} from "../../service/common.redis.service";
import {CommonRequestService} from "../../service/common.request.service";
import {sendApproveMsg} from "../../common/common";

@Controller('apply-admin/approve')
export class ApproveController{
    constructor(private readonly approveService: ApproveService, private readonly applyService: ApplyService, private readonly applyUserService: ApplyUserService, private readonly commonRedisService: CommonRedisService, private readonly commonRequestService: CommonRequestService) {

    }
    @Post('/add')
    async addApprove(@Body() approveDto: ApproveDto, @Res({ passthrough: true }) res: Response) {
        res.status(HttpStatus.OK);
        approveDto.id = uuid(32)
        if (!approveDto.applyId || !approveDto.applyAccountId || !approveDto.approveAccountId || !approveDto.deviceSn) {
            return new CommonResponseDto(ResCode.ERROR, 'applyId applyAccountId approveAccountId deviceSn 必填', null)
        }
        if (![ApproveStatus.PASSED, ApproveStatus.REJECTED].includes(approveDto.status)) {
            return new CommonResponseDto(ResCode.ERROR, 'status状态不正确', null)
        }
        try {
            const apply = await this.applyService.getOneById(approveDto.applyId)
            if (apply.status !== ApplyStatus.PENDING) {
                return new CommonResponseDto(ResCode.ERROR, '该申请已审批或已取消', null)
            }
            approveDto.approveTime = new Date().getTime() + ''
            let nextApproveAccountId = ''
            const approveIdArr = apply.approveAccountIdList.split(',')
            const index = approveIdArr.findIndex((id: string) => id == approveDto.approveAccountId)
            console.log('当前审批人：' + approveDto.approveAccountId + '，索引：' + index + '，所有审批人：' + apply.approveAccountIdList)
            if (index < approveIdArr.length - 1) {
                nextApproveAccountId = approveIdArr[index + 1]
            }
            // 如果有需要下一个审批人，给下一个审批人发送工作通知：审批消息
            if (nextApproveAccountId) {
                // @ts-ignore
                sendApproveMsg(nextApproveAccountId, [`${apply.applyUserInfo.name}申请使用[${apply.deviceInfo.deviceName}]${apply.deviceInfo.deviceType === 'dock' ? '机场' : '飞行器'}`,`使用时间：${apply.applyUseDate} ${apply.applyUseTimeRange}`,`申请人：${apply.applyUserInfo.name}`,`申请时间：${formatTime(Number(apply.applyTime))}`], {type: 'approve', status: ApplyStatus.PENDING}, {commonRedisService: this.commonRedisService, commonRequestService: this.commonRequestService})
            }
            let status
            if (nextApproveAccountId) {
                status = ApplyStatus.PENDING
            } else {
                if (approveDto.status === ApproveStatus.PASSED) {
                    status = ApplyStatus.PASSED
                } else {
                    status = ApplyStatus.REJECTED
                }
            }
            // 给申请人发送工作通知：当前审批消息
            (async () => {
                const user = await this.applyUserService.getOneByAccountId(approveDto.approveAccountId)
                // @ts-ignore
                sendApproveMsg(apply.applyAccountId, [`您的申请：${apply.applyUseDate} ${apply.applyUseTimeRange}使用[${apply.deviceInfo.deviceName}]${apply.deviceInfo.deviceType === 'dock' ? '机场' : '飞行器'}已被${user.name}审批`, `审批结果：${approveDto.status === ApproveStatus.PASSED ? '通过' : '拒绝'}`, `审批时间：${formatTime(Number(approveDto.approveTime))}`, `审批意见：${approveDto.approveRemark}`], {type: 'my', status}, {commonRedisService: this.commonRedisService, commonRequestService: this.commonRequestService})
            })();
            // 修改申请表中的审批状态,如果有下一个审批人，状态依然为待审批，否则就是当前审批状态(通过|拒绝)；审批表中添加一条审批记录；
            const result = await this.approveService.createOne(approveDto, nextApproveAccountId)
            if (result) {
                return new CommonResponseDto(ResCode.OK, '成功', result)
            } else {
                return new CommonResponseDto(ResCode.ERROR, '操作失败', null)
            }
        } catch(e){
            console.log(e)
            return new CommonResponseDto(ResCode.ERROR, '服务异常', null)
        }
    }

    @Get('/list-for-apply')
    async getApplyApproveList(@Query() query: {applyId: string}, @Res({ passthrough: true }) res: Response) {
        res.status(HttpStatus.OK);
        if (!query.applyId) {
            return new CommonResponseDto(ResCode.ERROR, 'applyId 必填', null)
        }
        try {
            const result = await this.approveService.getAllByApplyId(query.applyId)
            result.sort((a, b) => {
                return Number(b.approveTime) - Number(a.approveTime)
            })
            return new CommonResponseDto(ResCode.OK, '成功', result)
        } catch(e){
            console.log(e)
            return new CommonResponseDto(ResCode.ERROR, '服务异常', null)
        }
    }

    @Get('/list-for-approve')
    async getApproveListByApproveAccountId(@Query() query: {approveAccountId: string}, @Res({ passthrough: true }) res: Response) {
        res.status(HttpStatus.OK);
        if (!query.approveAccountId) {
            return new CommonResponseDto(ResCode.ERROR, 'approveAccountId 必填', null)
        }
        try {
            const result = await this.approveService.getAllByApproveAccountId(query.approveAccountId)
            return new CommonResponseDto(ResCode.OK, '成功', result)
        } catch(e){
            console.log(e)
            return new CommonResponseDto(ResCode.ERROR, '服务异常', null)
        }
    }
}
